package com.xiaochun.jiankangapp.activity

import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import com.xiaochun.jiankangapp.BuildConfig
import com.xiaochun.jiankangapp.R
import com.xiaochun.jiankangapp.base.BaseActivity
import com.xiaochun.jiankangapp.databinding.ActivityLoginBinding
import com.xiaochun.jiankangapp.extension.onClick
import com.xiaochun.jiankangapp.extension.showToast
import com.xiaochun.jiankangapp.extension.start
import kotlin.math.log

/**
 * 登录
 */
class LoginActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewBinding = setContentView<ActivityLoginBinding>()
//        if (BuildConfig.DEBUG) {
//            viewBinding.account.setText("15801127354")
//            viewBinding.pass.setText("xiaoqi111")
//        }
        loginViewModel.user.observe(this) {
            hideLoading()
            if (it != null) {
                start(MainActivity::class.java)
                finish()
            }
        }
        viewBinding.nopass.text = SpannableStringBuilder().let {
            it.append("还没有账号,")
            it.append(SpannableString("立即注册").apply {
                setSpan(
                    ForegroundColorSpan(getColor(R.color.color_primary)),
                    0,
                    length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            })
            it.append("新账户")
        }
        viewBinding.nopass.onClick {
            start(RegActivity::class.java)
        }
        viewBinding.login.setOnClickListener {
            login(viewBinding)
        }
        viewBinding.forget.onClick {
            start(ForgetPasswordActivity::class.java)
        }
    }

    private fun login(viewBinding: ActivityLoginBinding) {
        val name = viewBinding.account.text.toString()
        val pass = viewBinding.pass.text.toString()
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
            showToast("请输入账号和密码")
            return
        }
        showLoading()
        loginViewModel.login(name, pass)
    }
}